<template>
    <div class="h-full flex flex-col p-5 gap-5">
        <!-- 密码房间密码输入模态框 -->
        <room-pwd-modal :room="lockedRoom" @close="lockedRoom = undefined"/>

        <!-- 顶部用户面板 -->
        <user-panel :user="userStore._user!!" class="flex-shrink-0"/>

        <!-- 房间列表:加载状态 -->
        <div v-if="response.waiting" class="flex-grow flex items-center justify-center">
            <n-spin/>
        </div>
        <!-- 房间列表:展示状态 -->
        <n-scrollbar class="flex-grow" v-else>
            <room-card v-for="room in response.result" :room="room" @click="handleJoinRoom(room)" class="my-2"/>
        </n-scrollbar>

        <!-- 操作按钮 -->
        <div class="flex-shrink-0" v-if="userStore._user?.username === 'admin'">
            <n-button type="primary" block size="large" @click="handleCreateRoom">
                <template #icon><n-icon :size="16"><plus-icon/></n-icon></template>
                创建房间
            </n-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import PlusIcon from "@/components/icons/plus-icon.vue";
import RoomCard from "./components/room-card.vue";
import UserPanel from "./components/user-panel.vue";
import RoomPwdModal from "./components/room-pwd-modal.vue";

import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useMessage } from "naive-ui";
import { useUserStore } from "@/store";
import { fetchRoomList } from "@/api/module/room.api.ts";
import { ROOM_CREATE_ROUTE_NAME, ROOM_ROUTE_PATH } from "@/router/routes/room.route.ts";
import { useRequest } from "@/api/utils.ts";

import type { RoomSummaryModel } from "@/api/model/room.model.ts";

const router = useRouter();
const message = useMessage();
const userStore = useUserStore();

const { response, request } = useRequest(fetchRoomList, { defaultValue: [] });

const lockedRoom = ref<RoomSummaryModel>();

function handleJoinRoom(room: RoomSummaryModel) {
    if (room.userCount >= room.capacity) {
        return message.warning("房间人数已满");
    }
    if (room.locked) {
        lockedRoom.value = room;
        return;
    }
    router.push({
        path: ROOM_ROUTE_PATH,
        query: {
            rid: room.id
        }
    });
}

function handleCreateRoom() {
    router.push({ name: ROOM_CREATE_ROUTE_NAME });
}

onMounted(() => {
    request();
});

</script>

<style scoped>

</style>